from fastapi import APIRouter, Depends
from src.config.database import check_db_health
from src.config.settings import settings
from src.services.cache_service import CacheService

router = APIRouter(prefix="/health", tags=["健康检查"])

# 初始化缓存服务用于健康检查
cache_service = CacheService()

@router.get("/basic")
async def basic_health_check():
    """
    基础健康检查端点
    """
    return {
        "status": "healthy",
        "service": "LangChainGraph"
    }

@router.get("/detailed")
async def detailed_health_check():
    """
    详细健康检查端点
    返回数据库、缓存等组件的健康状态
    """
    # 检查数据库健康状态
    db_healthy = check_db_health()
    
    # 检查缓存健康状态
    cache_healthy = False
    try:
        # 尝试设置和获取一个测试值
        test_key = "health_check_test"
        test_value = "test"
        cache_service.set(test_key, test_value, ttl=10)  # 10秒过期
        cached_value = cache_service.get(test_key)
        cache_healthy = (cached_value == test_value)
        
        # 清理测试数据
        # 测试数据会在10秒后自动过期，无需手动清理
    except Exception:
        cache_healthy = False
    
    # 检查MCP服务状态（如果启用）
    mcp_status = {}
    if settings.MCP_ENABLED:
        mcp_status = {
            "enabled": True,
            "servers": settings.MCP_SERVERS or []
        }
    else:
        mcp_status = {
            "enabled": False
        }
    
    return {
        "status": "healthy" if (db_healthy and cache_healthy) else "degraded",
        "components": {
            "database": {
                "status": "healthy" if db_healthy else "unhealthy"
            },
            "cache": {
                "status": "healthy" if cache_healthy else "unhealthy"
            },
            "mcp": mcp_status
        },
        "timestamp": __import__('datetime').datetime.now().isoformat()
    }